package com.pms.dao;

import java.sql.ResultSet;
import java.sql.SQLException;


import com.pms.entity.Document;

import java.util.List;
import com.pms.util.DBHelp;
import com.pms.util.RowMapper;

public class DocumentDao {

	DBHelp<Document> db = new DBHelp<Document>();
	
	public void save(Document doc){
		String sql = "INSERT INTO t_doucument(title ,content, t_user_useid, t_project_proid) VALUES(?,?,?,?)";
		db.executeSQL(sql, doc.getTitle(), doc.getContent(), doc.getUserid(), doc.getProid());
	}

	public List<Document> findAll() {
		String sql="SELECT id,title,content,createtime,t_user_useid,t_project_proid FROM t_doucument";
		return db.executeQueryToList(sql.toString(), new DocumentRowMapper());
	}
	
	
	

	public Document findById(String docid) {
		String sql="SELECT id,title,content,createtime,t_user_useid,t_project_proid FROM t_doucument WHERE id=?";
		
		return db.executeQueryToObject(sql, new DocumentRowMapper(), docid);
	}

/*	public List<Document> fingByProId(String proid) {
		String sql="SELECT id,title,content,createtime,`t_user_useid`,t_project_proid FROM t_doucument WHERE `t_project_proid`=?";
		
		return db.executeQueryToList(sql,new DocumentRowMapper(), proid);
	}
	*/
	public List<Document> fingByProId(String proid) {
		String sql="SELECT t_doucument.id,t_doucument.title,t_doucument.content,t_doucument.createtime,t_user.`username`,t_project_proid FROM t_doucument LEFT JOIN t_user ON t_user.useid=t_doucument.t_user_useid WHERE t_doucument.t_project_proid=?";
		
		return db.executeQueryToList(sql, new RowMapper<Document>(){

			@Override
			public Document mapRow(ResultSet rs) throws SQLException {
				Document doc = new Document();
				doc.setDoid(rs.getString("id"));
			    doc.setContent(rs.getString("content"));
			    doc.setCreatetime(rs.getString("createtime"));
			    doc.setUsername(rs.getString("username"));
			    doc.setTitle(rs.getString("title"));
			    doc.setProid(rs.getString("t_project_proid"));
				return doc;
			}
			
			
		},proid);
	
	}
	
	
	private class DocumentRowMapper implements RowMapper<Document>{
		
		public Document mapRow(ResultSet rs) throws SQLException {
			Document doc = new Document();
			doc.setDoid(rs.getString("id"));
			doc.setTitle(rs.getString("title"));
		    doc.setContent(rs.getString("content"));
		    doc.setCreatetime(rs.getString("createtime"));
		    doc.setUserid(rs.getString("t_user_useid"));
		    doc.setProid(rs.getString("t_project_proid"));
			return doc;
		}
		
	}


	public void update(Document doc) {
		String sql="UPDATE t_doucument SET title=?,content=? WHERE id=?";
		db.executeSQL(sql.toString(),doc.getTitle(),doc.getContent(),doc.getDoid());
	}

	public void del(String doid) {
		String sql="DELETE FROM t_doucument WHERE id=?";
		db.executeSQL(sql.toString(),doid);
	}
	
	
}
